{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "5R6IJElm8xpl"
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "\n",
        "#Questao 1 - A\n",
        "\n",
        "radius = 9\n",
        "def calculate_x(x):\n",
        "  return x**(3/2)\n",
        "def first_derivative_of_x(x):\n",
        "  return (3/2) * (x**(1/2))\n",
        "def second_derivative_of_x(x):\n",
        "  return (3/4) * (x**(-(1/2)))\n",
        "def third_derivative_of_x(x):\n",
        "  return (-3/8)*(x**(-3/2))\n",
        "def fourth_derivative_of_x(x):\n",
        "  return (9/16)*(x**(-5/2))\n",
        "def fifth_derivative_of_x(x):\n",
        "  return (-45/32)*(x**(-7/2))\n",
        "\n",
        "def first_order_taylor(x):\n",
        "  return calculate_x(radius)+((first_derivative_of_x(radius)) * (x - radius))\n",
        "def second_order_taylor(x):\n",
        "  return first_order_taylor(x) + ((second_derivative_of_x(radius)/2) * ((x - radius)**2))\n",
        "def third_order_taylor(x):\n",
        "  return second_order_taylor(x) + ((third_derivative_of_x(radius)/6)*((x-radius)**3))\n",
        "def fourth_order_taylor(x):\n",
        "  return third_order_taylor(x) + ((fourth_derivative_of_x(radius)/24)*((x-radius)**4))\n",
        "\n",
        "\n",
        "def calc_values(func, x_values):\n",
        "  values_function=[]\n",
        "  for value in x_values:\n",
        "    values_function.append(func(value))\n",
        "  return values_function\n",
        "\n",
        "def calc_values_between_functions(func1, func2, x_values):\n",
        "  values_function=[]\n",
        "  for value in x_values:\n",
        "    func1_result = func1(value)\n",
        "    func2_result = func2(value)\n",
        "    values_function.append(func1_result - func2_result)\n",
        "  return values_function\n",
        "\n",
        "\n",
        "def question1a():\n",
        "  x_values = np.arange (0, 20, 1)\n",
        "  plt.plot(x_values, calc_values(calculate_x,x_values), label = \"function\")\n",
        "  plt.plot(x_values, calc_values(first_order_taylor,x_values), label = \"taylor first order\")\n",
        "  plt.plot(x_values, calc_values(second_order_taylor,x_values), label = \"taylor second order\")\n",
        "  plt.plot(x_values, calc_values(third_order_taylor,x_values), label = \"taylor third order\")\n",
        "  plt.plot(x_values, calc_values(fourth_order_taylor,x_values), label = \"taylor fourth order\")\n",
        "  plt.xlabel('x - axis')\n",
        "  plt.ylabel('y - axis')\n",
        "  plt.legend()\n",
        "  plt.show()\n",
        "\n",
        "question1a()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "eCNl5wjPC4EE"
      },
      "outputs": [],
      "source": [
        "#Questao 1 - B\n",
        "def inequality_of_taylor_in_fourth_order(x):\n",
        "  return (fifth_derivative_of_x(x)/(5*4*3*2))*((x-radius)**(5))\n",
        "\n",
        "def question1b():\n",
        "  x_values = np.arange(9,10,0.0001)\n",
        "  #plt.plot(x_values, calc_values_between_functions(calculate_x, first_order_taylor, x_values), label = \"Error in first order Taylor\" )\n",
        "  #plt.plot(x_values, calc_values_between_functions(calculate_x, second_order_taylor, x_values), label = \"Error in second order Taylor\" )\n",
        "  #plt.plot(x_values, calc_values_between_functions(calculate_x, third_order_taylor, x_values), label = \"Error in third order Taylor\" )\n",
        "  plt.plot(x_values, np.abs(calc_values_between_functions(calculate_x, fourth_order_taylor, x_values)), label = \"Error in fourth order Taylor\" )\n",
        "  plt.plot(x_values, np.abs(calc_values(inequality_of_taylor_in_fourth_order, x_values)), label = \"Taylor Inequality in fourth order\")\n",
        "  plt.xlabel('x - axis')\n",
        "  plt.ylabel('y - axis')\n",
        "  plt.legend()\n",
        "  plt.show()\n",
        "\n",
        "\n",
        "\n",
        "question1b()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9j4Zw7zpXgTx"
      },
      "outputs": [],
      "source": [
        "#Questao 2\n",
        "from math import e\n",
        "p_em_20 = 2.4 * (10**(-8))\n",
        "a = 0.0037\n",
        "radius_2 = 20\n",
        "\n",
        "def p_de_t(t):\n",
        "  return p_em_20 * (e**(a*(t-20)))\n",
        "\n",
        "def derivada_primeiro_pt(t):\n",
        "  return p_de_t(t) * a\n",
        "\n",
        "def derivada_segundo_pt(t):\n",
        "  return derivada_primeiro_pt(t) * a\n",
        "\n",
        "def first_order_taylor_2(t):\n",
        "  return p_de_t(radius_2) + ((derivada_primeiro_pt(radius_2))*(t-radius_2))\n",
        "\n",
        "def second_order_taylor_2(t):\n",
        "  return first_order_taylor_2(t) + ((derivada_segundo_pt(radius_2)/2) * ((t - radius_2)**2))\n",
        "#tem que passar os dois polinomios de taylor pro papel ou escrever aqui\n",
        "\n",
        "def question2b():\n",
        "   x_values = np.arange (-250, 1000, 1)\n",
        "   plt.plot(x_values, calc_values(p_de_t,x_values), label = \"p de t\")\n",
        "   plt.plot(x_values, calc_values(first_order_taylor_2,x_values), label = \"first order taylor\")\n",
        "   plt.plot(x_values, calc_values(second_order_taylor_2,x_values), label = \"second order taylor\")\n",
        "   plt.xlabel('Temperatura')\n",
        "   plt.ylabel('Resistividade')\n",
        "   plt.title(\"Questão 2 B\")\n",
        "   plt.legend()\n",
        "   plt.show()\n",
        "\n",
        "def question2c():\n",
        "  temp_range = []\n",
        "  x_values = np.arange(-250, 1000, 0.1)\n",
        "  for i in x_values:\n",
        "    error_in_i = p_de_t(i) - first_order_taylor_2(i)\n",
        "    if (error_in_i < p_de_t(i)*0.01) or (error_in_i == p_de_t(i)*0.01):\n",
        "      temp_range.append(round(i,1))\n",
        "  plt.plot(temp_range, calc_values(first_order_taylor_2,temp_range), label = \"first order taylor\")\n",
        "  plt.plot(temp_range, calc_values(p_de_t,temp_range), label = \"p de t\")\n",
        "  plt.xlabel('Temperatura')\n",
        "  plt.ylabel('Resistividade')\n",
        "  plt.suptitle(\"Questão 2 C\")\n",
        "  plt.title(f'Os valores vão de {temp_range[0]}°C até {temp_range[-1]}°C')\n",
        "  plt.legend()\n",
        "  plt.show()\n",
        "\n",
        "question2b()\n",
        "question2c()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XDfjyso8Xsyi"
      },
      "outputs": [],
      "source": [
        "#q3\n",
        "from math import cos as cos\n",
        "from math import pi as pi\n",
        "\n",
        "def g1(t,f=1.5):\n",
        "  return 1+cos((2*pi)*f*t)\n",
        "\n",
        "def g2(t):\n",
        "  return 1+ cos((3*pi)*t)+cos((6*pi)*t)\n",
        "\n",
        "def eg1(t, f=2.25):\n",
        "  return g1(t)*(e**(-2*pi*1j*f*t))\n",
        "\n",
        "def eg2(t, f=2.25):\n",
        "  return g2(t)*(e**(-2*pi*1j*f*t))\n",
        "\n",
        "\n",
        "f1 = lambda f: (\n",
        "    lambda t: eg1([0, 2.5, 0.1], f)\n",
        ")\n",
        "f1([0, 2.5])"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "a91F9bqpmfNK"
      },
      "outputs": [],
      "source": [
        "!sudo apt update\n",
        "!sudo apt install libcairo2-dev ffmpeg \\\n",
        "    texlive texlive-latex-extra texlive-fonts-extra \\\n",
        "    texlive-latex-recommended texlive-science \\\n",
        "    tipa libpango1.0-dev\n",
        "!pip install manim\n",
        "!pip install IPython --upgrade"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0VHLRvPjmTA7"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import random\n",
        "from matplotlib.animation import FuncAnimation\n",
        "from manim import *"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "88weXfJOonOr"
      },
      "outputs": [],
      "source": [
        "%%manim -qm -v WARNING g1_1\n",
        "from math import e as e\n",
        "\n",
        "class g1_1(Scene):  #ILLUSTRATING POLAR PLANE WITH A SINE CURVE\n",
        "    def construct(self):\n",
        "\n",
        "\n",
        "        e = ValueTracker(0.008) #Tracks the end value of both functions\n",
        "\n",
        "        plane = PolarPlane(radius_max=3).add_coordinates()\n",
        "        plane.shift(RIGHT*2)\n",
        "        graph1 = always_redraw(lambda :\n",
        "        ParametricFunction(lambda t : plane.polar_to_point(eg1(t), t),\n",
        "        t_range = [0, e.get_value()], color = GREEN)\n",
        "        )\n",
        "        dot1 = always_redraw(lambda : Dot(fill_color = YELLOW, fill_opacity = 0.8).scale(1).move_to(graph1.get_end())\n",
        "        )\n",
        "\n",
        "\n",
        "        axes = Axes(x_range = [0, 5, 1], x_length=3, y_range=[0,4,1], y_length=3).shift(LEFT*5)\n",
        "        axes.add_coordinates()\n",
        "        graph3 = always_redraw(\n",
        "            lambda : axes.plot(lambda x : g1(x),\n",
        "                       x_range = [0, e.get_value()],\n",
        "                       color = GREEN),\n",
        "        )\n",
        "        dot3 = always_redraw(lambda : Dot(fill_color = YELLOW, fill_opacity = 0.8).scale(1).move_to(graph3.get_end())\n",
        "        )\n",
        "\n",
        "      # Create a Text object to display the value\n",
        "          # Update the text position to be next to the dot\n",
        "        function_value = always_redraw(\n",
        "            lambda: DecimalNumber(num_decimal_places=2)\n",
        "            .set_value(g1(e.get_value()))\n",
        "            .next_to(dot3, RIGHT, buff=0.1)\n",
        "            .set_color(YELLOW)\n",
        "        ).add_background_rectangle()\n",
        "\n",
        "        title = MathTex(\"g_1(t) = 1 + cos(2\\pi f_st), f_s=1.5Hz\", color = GREEN).next_to(axes, UP, buff=0.2).scale(0.5)\n",
        "        time = MathTex(\"t = \", color = GREEN).next_to(title, DOWN, buff=0.2)\n",
        "        time_value = always_redraw(\n",
        "            lambda: DecimalNumber(num_decimal_places=3)\n",
        "            .set_value(e.get_value())\n",
        "            .next_to(time, RIGHT, buff=0.1)\n",
        "            .set_color(YELLOW)\n",
        "        ).add_background_rectangle()\n",
        "\n",
        "        e_time_value = always_redraw(\n",
        "            lambda: Tex(f\"{round(eg1(e.get_value()).real,2)} + {round(eg1(e.get_value()).imag,2)}i\")\n",
        "            .next_to(dot1, RIGHT, buff=0.1)\n",
        "            .set_color(YELLOW)\n",
        "        ).add_background_rectangle()\n",
        "\n",
        "        self.play(LaggedStart(\n",
        "            Create(axes), Write(title), Write(plane), Write(time),\n",
        "            run_time=1, lag_ratio=0.5)\n",
        "        )\n",
        "        self.add(graph1, graph3, dot1, dot3, function_value, time_value, e_time_value)\n",
        "        self.play(e.animate.set_value(4), run_time = 8, rate_func = linear)\n",
        "        self.wait()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "m22jmTjP3YOl"
      },
      "outputs": [],
      "source": [
        "%%manim -qm -v WARNING g2_1\n",
        "from math import e as e\n",
        "\n",
        "class g2_1(Scene):  #ILLUSTRATING POLAR PLANE WITH A SINE CURVE\n",
        "    def construct(self):\n",
        "\n",
        "\n",
        "        e = ValueTracker(0.008) #Tracks the end value of both functions\n",
        "\n",
        "        plane = PolarPlane(radius_max=3).add_coordinates()\n",
        "        plane.shift(RIGHT*2)\n",
        "        graph1 = always_redraw(lambda :\n",
        "        ParametricFunction(lambda t : plane.polar_to_point(eg2(t), t),\n",
        "        t_range = [0, e.get_value()], color = GREEN)\n",
        "        )\n",
        "        dot1 = always_redraw(lambda : Dot(fill_color = YELLOW, fill_opacity = 0.8).scale(1).move_to(graph1.get_end())\n",
        "        )\n",
        "\n",
        "\n",
        "        axes = Axes(x_range = [0, 5, 1], x_length=3, y_range=[0,4,1], y_length=3).shift(LEFT*5)\n",
        "        axes.add_coordinates()\n",
        "        graph3 = always_redraw(\n",
        "            lambda : axes.plot(lambda x : g2(x),\n",
        "                       x_range = [0, e.get_value()],\n",
        "                       color = GREEN),\n",
        "        )\n",
        "        dot3 = always_redraw(lambda : Dot(fill_color = YELLOW, fill_opacity = 0.8).scale(1).move_to(graph3.get_end())\n",
        "        )\n",
        "\n",
        "      # Create a Text object to display the value\n",
        "          # Update the text position to be next to the dot\n",
        "        function_value = always_redraw(\n",
        "            lambda: DecimalNumber(num_decimal_places=2)\n",
        "            .set_value(g2(e.get_value()))\n",
        "            .next_to(dot3, RIGHT, buff=0.1)\n",
        "            .set_color(YELLOW)\n",
        "        ).add_background_rectangle()\n",
        "\n",
        "        title = MathTex(\"g_2(t)\", color = GREEN).next_to(axes, UP, buff=0.2).scale(0.5)\n",
        "        time = MathTex(\"t = \", color = GREEN).next_to(title, DOWN, buff=0.2)\n",
        "        time_value = always_redraw(\n",
        "            lambda: DecimalNumber(num_decimal_places=3)\n",
        "            .set_value(e.get_value())\n",
        "            .next_to(time, RIGHT, buff=0.1)\n",
        "            .set_color(YELLOW)\n",
        "        ).add_background_rectangle()\n",
        "\n",
        "        e_time_value = always_redraw(\n",
        "            lambda: Tex(f\"{round(eg2(e.get_value()).real,2)} + {round(eg2(e.get_value()).imag,2)}i\")\n",
        "            .next_to(dot1, RIGHT, buff=0.1)\n",
        "            .set_color(YELLOW)\n",
        "        ).add_background_rectangle()\n",
        "\n",
        "        self.play(LaggedStart(\n",
        "            Create(axes), Write(title), Write(plane), Write(time),\n",
        "            run_time=1, lag_ratio=0.5)\n",
        "        )\n",
        "        self.add(graph1, graph3, dot1, dot3, function_value, time_value, e_time_value)\n",
        "        self.play(e.animate.set_value(4), run_time = 8, rate_func = linear)\n",
        "        self.wait()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "background_save": true
        },
        "id": "0aHwuCj1B5QJ"
      },
      "outputs": [],
      "source": [
        "#QUESTÃO 3 - 1A e 1B\n",
        "#-------------------\n",
        "\n",
        "# Definição dos sinais g1(t) e g2(t)\n",
        "fs = 1.5\n",
        "f = 2.25\n",
        "Ts = 4.0\n",
        "N = 500\n",
        "tk = np.linspace(0, Ts, N)\n",
        "g1_t = 1 + np.cos(2 * np.pi * fs * tk)\n",
        "g2_t = 1 + np.cos(3 * np.pi * tk) + np.cos(6 * np.pi * tk)\n",
        "\n",
        "# Criação da figura e dos eixos\n",
        "fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 8))\n",
        "fig.subplots_adjust(hspace=0.5)\n",
        "\n",
        "# Inicialização dos gráficos vazios\n",
        "line1, = ax1.plot([], [], 'b-')\n",
        "line2, = ax2.plot([], [], 'r-')\n",
        "vector, = ax2.plot([], [], 'g-')\n",
        "lines = [line1, line2, vector]\n",
        "\n",
        "# Função para inicialização dos gráficos\n",
        "def init():\n",
        "    ax1.set_xlim(0, Ts)\n",
        "    ax1.set_ylim(-2, 2)\n",
        "    ax1.set_xlabel('Tempo (s)')\n",
        "    ax1.set_ylabel('g1(t)')\n",
        "\n",
        "    ax2.set_xlim(-4, 4)\n",
        "    ax2.set_ylim(-2, 2)\n",
        "    ax2.set_xlabel('Re')\n",
        "    ax2.set_ylabel('Im')\n",
        "\n",
        "    for line in lines:\n",
        "        line.set_data([], [])\n",
        "\n",
        "    return lines\n",
        "\n",
        "# Função para atualização dos gráficos a cada quadro da animação\n",
        "def update(frame):\n",
        "    # Atualiza o gráfico g1(t) na parte de cima\n",
        "    line1.set_data(tk[:frame], g1_t[:frame])\n",
        "\n",
        "    # Calcula o vetor complexo gi(tk)*e^{−2*π*i*f*tk} na parte de baixo\n",
        "    gi_t_complex = g2_t[:frame] * np.exp(-2j * np.pi * f * tk[:frame])\n",
        "    line2.set_data(np.real(gi_t_complex), np.imag(gi_t_complex))\n",
        "\n",
        "    return lines\n",
        "\n",
        "# Criação das animações com intervalo de 50 ms entre os quadros (ajuste conforme necessário)\n",
        "ani1 = FuncAnimation(fig, update, frames=N, init_func=init, blit=True, interval=50)\n",
        "ani2 = FuncAnimation(fig, update, frames=N, init_func=init, blit=True, interval=50)\n",
        "\n",
        "# Exibição das animações\n",
        "from IPython.display import HTML\n",
        "HTML(ani1.to_jshtml())\n",
        "HTML(ani2.to_jshtml())\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1CRisqnnB50r"
      },
      "outputs": [],
      "source": [
        "#QUESTÃO 3 - 2\n",
        "#-------------------\n",
        "\n",
        "# Definição dos sinais g1(t) e g2(t)\n",
        "fs = 1.5\n",
        "f_values = np.arange(0, 5.01, 0.01)  # Valores de f variando de 0 a 5 com incremento de 0.01 Hz\n",
        "Ts = 4.0\n",
        "N = 500\n",
        "tk = np.linspace(0, Ts, N)\n",
        "g1_t = 1 + np.cos(2 * np.pi * fs * tk)\n",
        "g2_t = 1 + np.cos(3 * np.pi * tk) + np.cos(6 * np.pi * tk)\n",
        "\n",
        "# Criação da figura e dos eixos\n",
        "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))\n",
        "\n",
        "# Inicialização dos gráficos vazios\n",
        "line1, = ax1.plot([], [], 'r-')\n",
        "point1, = ax1.plot([], [], 'go')\n",
        "line2, = ax2.plot([], [], 'b-')\n",
        "lines = [line1, point1, line2]\n",
        "\n",
        "# Função para inicialização dos gráficos\n",
        "def init():\n",
        "    ax1.set_xlim(-2, 2)\n",
        "    ax1.set_ylim(-2, 2)\n",
        "    ax1.set_xlabel('Re')\n",
        "    ax1.set_ylabel('Im')\n",
        "    ax1.set_title('Gráfico 1b) para diferentes valores de f')\n",
        "\n",
        "    ax2.set_xlim(0, 5)\n",
        "    ax2.set_ylim(-2, 2)\n",
        "    ax2.set_xlabel('f (Hz)')\n",
        "    ax2.set_ylabel('Coordenada x do Centro de Massa')\n",
        "    ax2.set_title('Coordenada x do Centro de Massa vs. f')\n",
        "\n",
        "    for line in lines:\n",
        "        line.set_data([], [])\n",
        "\n",
        "    return lines\n",
        "\n",
        "# Função para calcular o centro de massa para uma frequência f\n",
        "def calculate_center_of_mass(f):\n",
        "    gi_t_complex = g2_t * np.exp(-2j * np.pi * f * tk)\n",
        "    integral = np.trapz(gi_t_complex, tk)\n",
        "    return (1 / Ts) * integral\n",
        "\n",
        "# Função para atualização dos gráficos a cada quadro da animação\n",
        "def update(frame):\n",
        "    f = f_values[frame]\n",
        "\n",
        "    # Calcula o gráfico 1b) para a frequência f\n",
        "    gi_t_complex = g2_t * np.exp(-2j * np.pi * f * tk)\n",
        "    line1.set_data(np.real(gi_t_complex), np.imag(gi_t_complex))\n",
        "\n",
        "    # Calcula o centro de massa para a frequência f\n",
        "    center_of_mass = calculate_center_of_mass(f)\n",
        "    point1.set_data(np.real(center_of_mass), np.imag(center_of_mass))\n",
        "\n",
        "    # Atualiza o gráfico 2a) na parte de baixo\n",
        "    line2.set_data(f_values[:frame], np.real([calculate_center_of_mass(f) for f in f_values[:frame]]))\n",
        "\n",
        "    # Adiciona o valor da frequência no gráfico da direita\n",
        "    freq_display.set_text('f = {:.2f} Hz'.format(f))\n",
        "\n",
        "    return lines\n",
        "\n",
        "# Criação do texto para o valor da frequência no gráfico da direita\n",
        "freq_display = ax2.text(4.9, 1.75, '', fontsize=12, ha='right', va='center', color='red')\n",
        "\n",
        "# Criação da animação com intervalo de 10 ms entre os quadros (ajuste conforme necessário)\n",
        "ani = FuncAnimation(fig, update, frames=len(f_values), init_func=init, blit=True, interval=10)\n",
        "\n",
        "# Exibição da animação\n",
        "display(HTML(ani.to_jshtml()))\n",
        "\n",
        "# Salvar a animação como um arquivo GIF na pasta do código\n",
        "ani.save('animacao.gif', writer='pillow')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Qbitg5OCB6Nq"
      },
      "outputs": [],
      "source": [
        "#QUESTÃO 3 - 3\n",
        "#-------------------\n",
        "\n",
        "# Definição dos sinais g1(t) e g2(t)\n",
        "fs = 1.5\n",
        "f_values = np.arange(0, 5.01, 0.01)  # Valores de f variando de 0 a 5 com incremento de 0.01 Hz\n",
        "Ts = 4.0\n",
        "N = 500\n",
        "tk = np.linspace(0, Ts, N)\n",
        "g1_t = 1 + np.sin(2 * np.pi * fs * tk)\n",
        "g2_t = 1 + np.sin(3 * np.pi * tk) + np.sin(6 * np.pi * tk)\n",
        "\n",
        "# Criação da figura e dos eixos\n",
        "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))\n",
        "\n",
        "# Inicialização dos gráficos vazios\n",
        "line1, = ax1.plot([], [], 'r-')\n",
        "point1, = ax1.plot([], [], 'go')\n",
        "line2, = ax2.plot([], [], 'b-')\n",
        "lines = [line1, point1, line2]\n",
        "\n",
        "# Função para inicialização dos gráficos\n",
        "def init():\n",
        "    ax1.set_xlim(-2, 2)\n",
        "    ax1.set_ylim(-2, 2)\n",
        "    ax1.set_xlabel('Re')\n",
        "    ax1.set_ylabel('Im')\n",
        "    ax1.set_title('Gráfico 1b) para diferentes valores de f')\n",
        "\n",
        "    ax2.set_xlim(0, 5)\n",
        "    ax2.set_ylim(-2, 2)\n",
        "    ax2.set_xlabel('f (Hz)')\n",
        "    ax2.set_ylabel('Coordenada x do Centro de Massa')\n",
        "    ax2.set_title('Coordenada x do Centro de Massa vs. f')\n",
        "\n",
        "    for line in lines:\n",
        "        line.set_data([], [])\n",
        "\n",
        "    return lines\n",
        "\n",
        "# Função para calcular o centro de massa para uma frequência f\n",
        "def calculate_center_of_mass(f):\n",
        "    gi_t_complex = g2_t * np.exp(-2j * np.pi * f * tk)\n",
        "    integral = np.trapz(gi_t_complex, tk)\n",
        "    return (1 / Ts) * integral\n",
        "\n",
        "# Função para atualização dos gráficos a cada quadro da animação\n",
        "def update(frame):\n",
        "    f = f_values[frame]\n",
        "\n",
        "    # Calcula o gráfico 1b) para a frequência f\n",
        "    gi_t_complex = g2_t * np.exp(-2j * np.pi * f * tk)\n",
        "    line1.set_data(np.real(gi_t_complex), np.imag(gi_t_complex))\n",
        "\n",
        "    # Calcula o centro de massa para a frequência f\n",
        "    center_of_mass = calculate_center_of_mass(f)\n",
        "    point1.set_data(np.real(center_of_mass), np.imag(center_of_mass))\n",
        "\n",
        "    # Atualiza o gráfico 2a) na parte de baixo\n",
        "    line2.set_data(f_values[:frame], np.real([calculate_center_of_mass(f) for f in f_values[:frame]]))\n",
        "\n",
        "    # Adiciona o valor da frequência no gráfico da direita\n",
        "    freq_display.set_text('f = {:.2f} Hz'.format(f))\n",
        "\n",
        "    return lines\n",
        "\n",
        "# Criação do texto para o valor da frequência no gráfico da direita\n",
        "freq_display = ax2.text(4.9, 1.75, '', fontsize=12, ha='right', va='center', color='red')\n",
        "\n",
        "# Criação da animação com intervalo de 10 ms entre os quadros (ajuste conforme necessário)\n",
        "ani = FuncAnimation(fig, update, frames=len(f_values), init_func=init, blit=True, interval=10)\n",
        "\n",
        "# Exibição da animação\n",
        "display(HTML(ani.to_jshtml()))\n",
        "\n",
        "# Salvar a animação como um arquivo GIF na pasta do código\n",
        "ani.save('animacao.gif', writer='pillow')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OMyv1PO9yORi"
      },
      "source": [
        "Questão 4 - A  "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9QRES0bTvtNv"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "# Função que calcula o módulo da série de Laurent em torno de z=1\n",
        "def laurent_series(z):\n",
        "    A = -1/2\n",
        "    B = 3/2\n",
        "    return np.abs(A / (z - 1) + B / (z - 5))\n",
        "\n",
        "# Criação de uma malha de pontos no plano complexo\n",
        "x = np.linspace(-10, 10, 500)\n",
        "y = np.linspace(-10, 10, 500)\n",
        "X, Y = np.meshgrid(x, y)\n",
        "Z = X + 1j * Y\n",
        "\n",
        "# Calcula o módulo da série para todos os pontos da malha\n",
        "Z_series = laurent_series(Z)\n",
        "\n",
        "# Criação do gráfico mostrando apenas o contorno onde o módulo é igual a 1\n",
        "plt.figure(figsize=(8, 6))\n",
        "plt.contour(X, Y, Z_series, levels=[1], colors='blue')\n",
        "plt.xlabel('Parte Real')\n",
        "plt.ylabel('Parte Imaginária')\n",
        "plt.title('Contorno da Região de Convergência da Série de Laurent em torno de z = 1')\n",
        "plt.axhline(0, color='black', linewidth=0.5)\n",
        "plt.axvline(0, color='black', linewidth=0.5)\n",
        "plt.grid(color='gray', linestyle='--', linewidth=0.5)\n",
        "plt.xlim(0, 7.5)\n",
        "plt.ylim(-2.5, 2.5)\n",
        "plt.show()\n",
        "\n"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}